package com.jk.videoplayer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {

    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            surfaceView = (SurfaceView) findViewById(R.id.surface);
        //运行时权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
            SurfaceHolder holder = surfaceView.getHolder();
            holder.addCallback(this);
        }else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
        }
        surfaceView.setOnClickListener(v -> new Intent(this,VideoActivity.class));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults[0]== PackageManager.PERMISSION_GRANTED) {
            surfaceView.getHolder().addCallback(this);
        }else {
            finish();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(new File(Environment.getExternalStorageDirectory(), "javaandroid01.wmv").getAbsolutePath());
            mediaPlayer.setDisplay(holder);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mediaPlayer.release();
        mediaPlayer=null;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        ViewGroup.LayoutParams params = surfaceView.getLayoutParams();
        params.width=mp.getVideoWidth();
        params.height=mp.getVideoHeight();
        surfaceView.setLayoutParams(params);

    }
}
